package cn.middle.remote.handler.client;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.middle.remote.Listener;
import cn.middle.remote.config.ClientConfig;
import cn.middle.remote.handler.business.ProcessingHandler;
import cn.middle.remote.message.HeartbeatPingSignal;
import cn.middle.remote.message.LoginSignal;
import cn.middle.remote.serialization.Serialization;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;

public abstract class ClientProcessingHandler<T extends Listener> implements ProcessingHandler {

	private ClientConfig config;
	
	protected Serialization serialization;
	
	protected T listener;
	
	
	private static final Logger log = LoggerFactory.getLogger(ClientProcessingHandler.class);
	//@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
			// 转型
			IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
			//String eventType = null;
			switch (idleStateEvent.state()) {
			case READER_IDLE:
				//eventType = "读空闲";
				break;
			case WRITER_IDLE:
				//eventType = "写空闲";
				break;
			case ALL_IDLE:
				//eventType = "读写空闲";
				heartBeat(ctx);
				break;
			}

		}
	}
	
	public void setListener(T  t) {
		listener = t;
	}
	
	public T getListener() {
		return listener;
	}
	
	public void heartBeat(ChannelHandlerContext ctx) {
		String msgId = UUID.randomUUID().toString();
		ctx.writeAndFlush(new HeartbeatPingSignal(msgId)); //发送心跳
		log.info(msgId + " : " + HeartbeatPingSignal.PING);
	}
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		if(config != null) {  //注册登陆
			LoginSignal login = new LoginSignal();
			login.setClientId(config.getClientId());
			login.setPassword(config.getPassword());
			login.setUsername(config.getUsrname());
			ctx.channel().writeAndFlush(login);
		}
	}
	
	public void setConfig(ClientConfig config) {
		this.config = config;
	}

	public Serialization getSerialization() {
		return serialization;
	}

	public void setSerialization(Serialization serialization) {
		this.serialization = serialization;
	}

}
